<?php
class Wee_Logging_Model_Mysql4_Event extends Mage_Core_Model_Mysql4_Abstract{
    protected function _construct(){
        $this -> _init('wee_logging/event', 'log_id');
    }
    protected function _beforeSave(Mage_Core_Model_Abstract $event){
        $event -> setData('ip', ip2long($event -> getIp()));
        $event -> setTime($this -> formatDate($event -> getTime()));
    }
    public function rotate($lifetime){
        try{
            $this -> beginTransaction();
            $table = $this -> getTable('wee_logging/event');
            $clearBefore = $this -> formatDate(time() - $lifetime);
            $latestLogEntry = $this -> _getWriteAdapter() -> fetchOne("SELECT log_id FROM {$table} WHERE `time` < '{$clearBefore}' ORDER BY 1 DESC LIMIT 1");
            if (!$latestLogEntry){
                return;
            }
            $archive = Mage :: getModel('wee_logging/archive');
            $archive -> createNew();
            $csv = fopen($archive -> getFilename(), 'w');
            foreach ($this -> _getWriteAdapter() -> fetchAll("SELECT *, INET_NTOA(ip) FROM {$table} WHERE log_id <= {$latestLogEntry}") as $row){
                fputcsv($csv, $row);
            }
            fclose($csv);
            $this -> _getWriteAdapter() -> query("DELETE FROM {$table} WHERE log_id <= {$latestLogEntry}");
            $this -> commit();
        }
        catch (Exception $e){
            $this -> rollBack();
        }
    }
    public function getAllFieldValues($field, $order = true){
        return $this -> _getReadAdapter() -> fetchCol("SELECT DISTINCT {$this->_getReadAdapter()->quoteIdentifier($field)} FROM {$this->getMainTable()}" . (null !== $order ? ' ORDER BY 1' . ($order ? '' : ' DESC') : ''));
    }
    public function getUserNames(){
        $select = $this -> _getReadAdapter() -> select() -> distinct() -> from(array('admins' => $this -> getTable('admin/user')), 'username') -> joinInner(array('events' => $this -> getTable('wee_logging/event')), 'admins.username = events.user', array());
        return $this -> _getReadAdapter() -> fetchCol($select);
    }
    public function getEventChangeIds($eventId){
        $adapter = $this -> _getReadAdapter();
        $select = $adapter -> select() -> from($this -> getTable('wee_logging/event_changes'), array('id')) -> where('event_id = ?', $eventId);
        return $adapter -> fetchCol($select);
    }
}
